<?php

class Avatar_EditController extends User_EditController {
	public function photoAction() {
		parent::photoAction ();
		$tmp_auth = $this->_helper->requireAuth ()->setNoForward ();
		$this->view->web_cam_on = $tmp_auth->setAuthParams ( 'avatar', null, 'web_cam' )->isValid ();
		$this->view->avatar_collection_on = $tmp_auth->setAuthParams ( 'avatar', null, 'avatarcollection' )->isValid ();
	}
	
	public function getwebcamAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'avatar', null, 'web_cam' )->isValid ())
			return;
		$this->_helper->layout->setLayout ( 'default-simple' );
		$this->renderScript ( '_getwebcam.tpl' );
	
	}
	public function savewebcamAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'avatar', null, 'web_cam' )->isValid ())
			return;
		$this->_helper->layout->setLayout ( 'default-simple' );
		$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
		$filename = rand () . '.jpg';
		$fullfile = $path . DIRECTORY_SEPARATOR . $filename;
		$result = @file_put_contents ( $fullfile, file_get_contents ( 'php://input' ) );
		if ($result) {
			try {
				$this->_saveavatar ( $fullfile );
			} 

			// If an exception occurred within the image adapter, it's probably an invalid image
			catch ( Engine_Image_Adapter_Exception $e ) {
				$db->rollBack ();
				return $this->_helper->json ( array ('result' => false, 'message' => Zend_Registry::get ( 'Zend_Translate' )->_ ( 'The uploaded file is not supported or is corrupt.' ) ) );
			}
			return $this->_helper->json ( array ('result' => true ) );
		} else {
			return $this->_helper->json ( array ('result' => false, 'message' => 'ERROR: Failed to write data to file, check permissions' ) );
		}
	}
	
	public function getavatarcollectionAction() {
		if (! ! ! $this->_helper->requireAuth ()->setAuthParams ( 'avatar', null, 'avatarcollection' )->isValid ())
			return;
		$this->_helper->layout->setLayout ( 'default-simple' );
		$this->view->collections = $collections = Engine_Api::_ ()->getDbtable ( 'avatarcollections', 'avatar' )->fetchAll ( 'name desc' );
		if (count ( $collections )) {
			if (! $collection_id = $this->_getParam ( 'collection_id' )) {
				$this->view->current_collection = $current_collection = $collections->current ();
				$collection_id = $current_collection->avatarcollection_id;
			} else {
				if (($this->view->current_collection = $collections->getRowMatching ( 'avatarcollection_id', $collection_id )) == null) {
					$this->_forward ( 'requiresubject', 'error', 'core' );
					return;
				}
			}
			$this->view->avatars = $avatars = Engine_Api::_ ()->getDbtable ( 'avatars', 'avatar' )->fetchAll ( array ('avatarcollection_id = ?' => $collection_id ) );
		
		}
	}
	
	public function selectAction() {
		$this->_helper->layout->setLayout ( 'default-simple' );
		try {
			$avatar_id = $this->_getParam ( 'avatar_id' );
			$avatar = Engine_Api::_ ()->getDbtable ( 'avatars', 'avatar' )->fetchRow ( array ('avatar_id = ?' => $avatar_id ) );
			if (count ( $avatar ) != 1)
				throw new Engine_Exception ( 'Invalid Avatar Id' );
			
			$file_dest = APPLICATION_PATH . '/application/modules/Avatar/externals/avatarcollections/' . $avatar->avatarcollection_id . '/' . 'avatar_' . $avatar->avatar_id . '.' . $avatar->extension;
			
			$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
			$filename = rand () . ".{$avatar->extension}";
			$fullfile = $path . DIRECTORY_SEPARATOR . $filename;
			if (! copy ( $file_dest, $fullfile ))
				throw new Engine_Exception ( 'Cann\'t copy avatar file.' );
			$this->_saveavatar ( $fullfile );
		} catch ( Exception $e ) {
			throw $e;
		}
		$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 1, 'parentRefresh' => 2, 'messages' => array ('' ) ) );
		return;
	}
	
	private function _saveavatar($fullfile) {
		try {
			$user = Engine_Api::_ ()->core ()->getSubject ();
			$db = $user->getTable ()->getAdapter ();
			$db->beginTransaction ();
			
			$fileElement = array ('tmp_name' => $fullfile );
			
			$user->setPhoto ( $fileElement );
			
			$iMain = Engine_Api::_ ()->getItem ( 'storage_file', $user->photo_id );
			
			// Insert activity
			$action = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->addActivity ( $user, $user, 'profile_photo_update', '{item:$subject} added a new profile photo.' );
			
			// Hooks to enable albums to work
			if ($action) {
				$event = Engine_Hooks_Dispatcher::_ ()->callEvent ( 'onUserProfilePhotoUpload', array ('user' => $user, 'file' => $iMain ) );
				
				$attachment = $event->getResponse ();
				if (! $attachment)
					$attachment = $iMain;
				
		// We have to attach the user himself w/o album plugin
				Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->attachActivity ( $action, $attachment );
			}
			
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	
	}
}